package com.easy.interceptor;

import com.easy.common.exception.ExceptionEnum;
import com.easy.common.util.Result;
import com.easy.common.util.Tools;
import com.easy.propertis.LoginInterceptorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: CoolPro
 * @Description:
 * @Time: 2024-04-23 14:54
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private RestTemplate restTemplate = new RestTemplate();
    @Value("${sso.ssoUrl}")
    private String ssoUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头信息，判断jwt是否有效
        if (1 == 1) return true;
        if("app".equals(request.getHeader("type"))) return true;
        if (request.getMethod().equals("OPTIONS")) return true;
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(ExceptionEnum.JWT_FAIL.getCode());
            response.setContentType("application/json;character=utf-8");
            response.getWriter().write(Tools.object2Json(Result.error(ExceptionEnum.JWT_FAIL)));
            return false;
        } else {
//            请求验证token
            Result result = restTemplate.getForObject(ssoUrl + "?token=" + token, Result.class);
            System.out.println(result);
            switch (result.getCode()) {
                case 200:
                    return true;
                case 30001:
                    //无效
                    response.setStatus(ExceptionEnum.JWT_FAIL.getCode());
                    response.setContentType("application/json;character=utf-8");
                    response.getWriter().write(Tools.object2Json(Result.error(ExceptionEnum.JWT_FAIL)));
                    System.out.println("jwt校验失败");
                    return false;
                case 30002:
                    //超时
                    response.setStatus(ExceptionEnum.JWT_OUT_TIME.getCode());
                    response.setContentType("application/json;character=utf-8");
                    response.getWriter().write(Tools.object2Json(Result.error(ExceptionEnum.JWT_OUT_TIME)));
                    System.out.println("请求超时");
                    return false;
                default:
                    return false;
            }
        }
    }

}
